from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.contrib.auth.decorators import login_required

from .form import JobPositionForm
from .models import JobPosition,ApplyRecord

# Create your views here.
@require_http_methods(["GET", "POST"])
def job_apply_list(request):
    jobs = JobPosition.objects.all()
    if request.method == 'GET':
        return render(request, 'job_apply_manage/job_apply.html', context={'jobs': jobs})


@login_required
@require_http_methods(["POST"])
def apply_job(request, job_id):
    try:
        job = JobPosition.objects.get(id=job_id)
        # 这里添加申请记录的逻辑
        records= ApplyRecord.objects.filter(user=request.user, job=job)
        if records.exists():
            return JsonResponse({
                'status': 'error',
                'message': '您已经申请过该职位'
            }, status=400)
        ApplyRecord.objects.create(
            user=request.user,
            job=job,
            status='pending'
        )

        return JsonResponse({
            'status': 'success',
            'message': '申请已提交成功！'
        })
    except JobPosition.DoesNotExist:
        return JsonResponse({
            'status': 'error',
            'message': '职位不存在'
        }, status=404)
    except Exception as e:
        return JsonResponse({
            'status': 'error',
            'message': str(e)
        }, status=500)
def search_job(request):
    keyword = request.GET.get('keyword')
    jobs = JobPosition.objects.filter(
        Q(title__icontains=keyword) | Q(description__icontains=keyword) | Q(company__icontains=keyword)
    )
    return render(request, 'job_apply_manage/research_result.html',{'jobs': jobs})
def help(request):
    return render(request, 'help.html')
@login_required
@require_http_methods(["GET", "POST"])
def apply_record(request):
    if request.method=='GET':
        applications = ApplyRecord.objects.filter(user=request.user).distinct()
        return render(request, 'job_apply_manage/apply_record.html',{'applications': applications})

@require_http_methods(["GET", "POST"])
def add_job(request):
    if request.method=='GET':
        return render(request, 'company/add_job.html')
    else:
        form = JobPositionForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data['title']
            company = form.cleaned_data['company']
            location = form.cleaned_data['location']
            salary_range = form.cleaned_data['salary_range']
            description = form.cleaned_data['description']
            requirements = form.cleaned_data['requirements']

            job = JobPosition.objects.create(
                title=title,
                company=company,
                location=location,
                salary_range=salary_range,
                description=description,
                requirements=requirements
            )
            return JsonResponse({
                'status': 'success',
                'message': '职位添加成功',
                'job_id': job.id
            })
        else:
            return JsonResponse({
                'status': 'error',
                'message': f'发布过程中出现错误：',
            }, status=500)
@require_http_methods(["GET", "POST"])
def check_apply_record(request):
    if request.method == 'GET':
        applications = ApplyRecord.objects.filter()
        return render(request, 'company/check_apply.html', {'applications': applications})
def accept_application(request, application_id):
    try:
        application = ApplyRecord.objects.get(id=application_id)
        application.status = 'accepted'
        application.save()
        return JsonResponse({'status': 'success'})
    except ApplyRecord.DoesNotExist:
        return JsonResponse({'status': 'error', 'message': '申请记录不存在'})

def reject_application(request, application_id):
    try:
        application = ApplyRecord.objects.get(id=application_id)
        application.status = 'rejected'
        application.save()
        return JsonResponse({'status': 'success'})
    except ApplyRecord.DoesNotExist:
        return JsonResponse({'status': 'error', 'message': '申请记录不存在'})